package gttp.nspa.server.adm.rpc;

import gttp.nspa.client.adm.rpc.ICustomerService;
import gttp.nspa.server.dao.DAO;
import gttp.nspa.server.dao.DAOs;
import gttp.nspa.server.dao.FilterBuilder;
import gttp.nspa.shared.om.Customer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CustomerService implements ICustomerService {

    protected final DAO<Customer> custDAO;

    public CustomerService() {
        custDAO = DAOs.customer;
    }

    public Customer load(long id) {
        return custDAO.load(id);
    }

    public void save(Customer c) {
        custDAO.save(c);
    }

    public void delete(long id) {
        custDAO.delete(id);
    }

    public void delete(Long[] ids) {
        custDAO.delete(Arrays.asList(ids));
    }

    protected FilterBuilder buildFilter(String name, String address, String phone, String email) {
        FilterBuilder fb = new FilterBuilder();
        if (name != null) {
            fb.eq("name", name);
        }
        if (address != null) {
            fb.eq("address", address);
        }
        if (phone != null) {
            fb.eq("phone", phone);
        }
        if (email != null) {
            fb.eq("email", email);
        }
        return fb;
    }

    public List<Customer> listBy(int offset, int limit, String[] orders) {
        return listBy(null, null, null, null, offset, limit, orders);
    }

    public List<Customer> listBy(String name,
                                 String address,
                                 String phone,
                                 String email,
                                 int offset,
                                 int limit,
                                 String[] orders) {
        FilterBuilder fb = buildFilter(name, address, phone, email);
        Iterator<Customer> it = custDAO.load(offset, limit, orders, fb.build());
        List<Customer> list = new ArrayList<>();
        while (it.hasNext()) {
            list.add(it.next());
        }
        return list;
    }

    public Customer create(String name, String phone, String address, String email) {
        Customer cust = new Customer();
        cust.setName(name);
        cust.setPhone(phone);
        cust.setAddress(address);
        cust.setEmail(email);
        custDAO.save(cust);
        return cust;
    }

}
